#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMap>
#include <QList>
#include <QDebug>
#include "Game.h"
#include "Player.h"
#include <QTableWidgetItem>

namespace Ui {
    class MainWindow;
}

class TableWidgetNumberItem : public QTableWidgetItem
{
  public:
    TableWidgetNumberItem(float val)
      : QTableWidgetItem(QString::number(val))
    {}

    bool operator<(const QTableWidgetItem& other) const
    {
      const TableWidgetNumberItem *rhs(dynamic_cast<const TableWidgetNumberItem*>(&other));
      if (rhs != NULL)
      {
        return text().toFloat() < rhs->text().toFloat();
      }
      return false;
    }
};

class QPushButton;
class PlayerSelectDlg;
class TurnScoreSelectDlg;
class NewPlayerDlg;
class MainWindow : public QMainWindow
{
    Q_OBJECT

  public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    void loadRosterFile(const QString& filename);

  public slots:
    void onNewRoster();
    void onOpenRoster();
    void onSaveRoster();
    void onQuit();
    void onAddPlayer();
    void onRemovePlayers();

    // Test Methods


    void onSelectAll();
    void onClearSelected();
    void onGenerateBracket();
    void onBracketGameSelected();

  protected:
    struct Tournament
    {
      QMap<QString, Player> mRoster;
      QList<Player> mLosers;
      QList<Game> mWinningGames, mLosingGames;
      Player mFinalsLoser;
      Game mCurrentGame;
      int mNumWinningByes, mNumLosingByes;
      int mNumWinningGames, mNumLosingGames;
      bool mLosingPhase;

      Tournament() : mFinalsLoser("") {}
    };

    void setupConnections();
    void closeEvent(QCloseEvent *e);
    bool readRosterFile(const QString& file);
    bool readTournamentFile(const QString& file);
    void addRosterToTable(const QMap<QString, Player>& roster);
    void addPlayerToRosterTable(const QString& name, float rating, int games, int rounds, int bagsmade, int points);
    void addPlayerToRosterTable(const Player& player);
    void setupRosterTable();
    void clearRosterTable();
    void scoreRoster(const QList<Tournament>& tournaments);
    void writeRosterFile(const QString& filename) const;
    QPushButton* createGameBtn(int x, int y, int w, int h, const QString& p1, const QString& p2, bool bye, int r, int g);
    void generateBracket(QList<Player>& players);

    QMap<QString, Player> mRoster;
    QList<Tournament> mTournaments;
    QList<QPushButton*> mCurrentTournamentGames;
    Tournament mCurrentTournament;
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
